package quq.missq.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import quq.missq.BaseActivity;
import quq.missq.Constants;
import quq.missq.R;
import quq.missq.adapter.AlbumAdapter;
import quq.missq.beans.Album;
import quq.missq.beans.AlbumBean;
import quq.missq.utils.UserTools;
import quq.missq.utils.VolleyTool;

/**
 * Created by River on 8/13/15.
 */
public class MyAlbumActivity extends BaseActivity implements VolleyTool.HTTPListener,
        SwipeRefreshLayout.OnRefreshListener,View.OnClickListener{

    private RecyclerView mRecyclerView;
    private LinearLayoutManager mLinearLayoutManager;
    private AlbumAdapter adapter;
    private SwipeRefreshLayout mRefreshLayout;
    private View mFootView;
    private LinkedList<Album> results;
    private int maxResults = 10;
    private int currentPage = 1;
    private ImageView mBack;
    private ImageView mAdd;
    private FrameLayout fl_empty;
    private TextView tv_content1;
    private TextView tv_content2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_album_activity);
        currentPage = 1;
        initView();
        initData();
        initListener();
        loadNetworkData();
    }

    private void initView(){
        mRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.refreshLayout);
        mRecyclerView = (RecyclerView)findViewById(R.id.recyclerView);
        mLinearLayoutManager =  new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mBack = (ImageView)findViewById(R.id.back);
        mAdd = (ImageView)findViewById(R.id.add);

        fl_empty = (FrameLayout) findViewById(R.id.fl_empty);
        tv_content1 = (TextView) findViewById(R.id.tv_content1);
        tv_content2 = (TextView) findViewById(R.id.tv_content2);
    }

    private void initData(){
        results = new LinkedList<>();
        adapter = new AlbumAdapter(this);
        adapter.setData(results);
        mRecyclerView.setAdapter(adapter);
        mRefreshLayout.setColorSchemeResources(R.color.red, R.color.red,R.color.red,R.color.red);
    }

    private void loadNetworkData(){
        Map<String,String> params = new HashMap<>();
        params.put("uid", UserTools.getUser(this).getId()+"");
        params.put("pn",currentPage+"");
        params.put("maxResults",maxResults+"");
        VolleyTool.get(this,Constants.MY_ALBUM_URL, params, this, Constants.MY_ALBUM, AlbumBean.class);
    }

    private void initListener(){
        mBack.setOnClickListener(this);
        mAdd.setOnClickListener(this);
        mRefreshLayout.setOnRefreshListener(this);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && mLinearLayoutManager.findLastVisibleItemPosition()+1 == adapter.getItemCount()) {
                    operateFootView(true);
                    currentPage = currentPage+1;
                    loadNetworkData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    private void operateFootView(boolean isDisplay){
        if(mFootView == null){
            mFootView = mRecyclerView.findViewWithTag("footView");
        }
        if(isDisplay){
            mFootView.setVisibility(View.VISIBLE);
        }else {
            mFootView.setVisibility(View.GONE);
        }
    }

    @Override
    public <T> void onResponse(T t, int requestCode) {
        AlbumBean bsBean = (AlbumBean)t;
        if(bsBean.getCode() >= 0){
            LinkedList<Album> beans = bsBean.getData().getResults();
            fl_empty.setVisibility(View.GONE);
            if(currentPage == 1){
                if(mRefreshLayout.isShown()){
                    mRefreshLayout.setRefreshing(false);
                }
                adapter.getData().clear();
                adapter.getData().addAll(0, beans);
                if(beans.size()==0){
                    fl_empty.setVisibility(View.VISIBLE);
                    tv_content1.setText("你的相册还是空空如也哦,马上去创");
                    tv_content2.setText("建一个相册吧!");
                }
                adapter.notifyDataSetChanged();
            }else{
                if(beans.size() > 0){
                    int startPosition = adapter.getItemCount();
                    adapter.getData().addAll(beans);
                    //adapter.notifyDataSetChanged();
                    adapter.notifyItemRangeInserted(startPosition, beans.size());
                }else{
                    if(results.size() > 10){
                        showToast("已加载完所有");
                    }
                }
                operateFootView(false);
            }
        }else{
            showToast(bsBean.getMessage());
        }
    }

    @Override
    public void onErrorResponse(VolleyError error, int requestCode) {

    }



    @Override
    public void onRefresh() {
        currentPage = 1;
        loadNetworkData();
        mRefreshLayout.setRefreshing(false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back:
                finish();
                break;
            case R.id.add:
                Intent intent = new Intent();
                intent.putExtra("title","创建相册");
                intent.setClass(this,AddAlbumActivity.class);
                startActivityForResult(intent, 1);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == RESULT_OK && requestCode == 1){
            Album album = (Album)data.getExtras().getSerializable("album");
            results.addFirst(album);
            adapter.notifyItemInserted(0);
        }else if(resultCode == RESULT_OK && requestCode == 0){
            adapter.notifyDataSetChanged();
        }
    }

//    @Override
//    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
//        super.onCreateContextMenu(menu, v, menuInfo);
//        // if(((AdapterContextMenuInfo)menuInfo).position > 0){ m,
//        //getMenuInflater().inflate(R.menu.album_message, menu);
//        // }
//    }
//
//    @Override
//    public boolean onContextItemSelected(MenuItem item) {
//        int id = (int)adapter.getItemId(((AdapterViewCompat.AdapterContextMenuInfo) item.getMenuInfo()).position);
//        if (item.getItemId() == R.id.delete_album) {
//            adapter.getData().remove(adapter.getData().get(id));
//            adapter.notifyItemRemoved(id);
//        } else if (item.getItemId() == R.id.update_album) {
//        }
//
////        EMConversation tobeDeleteCons = adapter.getItem(((AdapterContextMenuInfo) item.getMenuInfo()).position);
////        // 删除此会话
////        EMChatManager.getInstance().deleteConversation(tobeDeleteCons.getUserName(), tobeDeleteCons.isGroup(), deleteMessage);
////        InviteMessgeDao inviteMessgeDao = new InviteMessgeDao(getActivity());tatgit
////        inviteMessgeDao.deleteMessage(tobeDeleteCons.getUserName());
////        adapter.remove(tobeDeleteCons);
////        adapter.notifyDataSetChanged();
////
////        // 更新消息未读数
////        ((MainActivity) getActivity()).updateUnreadLabel();
//
//        return false;
//    }

//    AlertDialog dialog = new AlertDialog.Builder(this,R.style.ohther_CustomDialog).setTitle("提醒").setMessage("删除收藏")
//            .setPositiveButton("取消", new DialogInterface.OnClickListener() {
//                @Override
//                public void onClick(DialogInterface dialog, int which) {
//                    dialog.dismiss();
//                }
//            }).setNegativeButton("确定", new DialogInterface.OnClickListener() {
//                @Override
//                public void onClick(DialogInterface dialog, int which) {
//                    deleteCollect(result.get(position).Id,result.get(position).IsScreening);
//                    result.remove(index);
//                    collectAdapter.notifyDataSetChanged();
//                    UIHelper.showToastSafe("删除成功");
//                    dialog.dismiss();
//                }
//            }).show();

}
